import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'

// 获取二级路由部署路径，与 vite.config.ts 中的 base 保持一致
const getBasePath = () => {
  // 从环境变量获取
  const envBase = import.meta.env.VITE_BASE_URL
  if (envBase) {
    // 确保以 / 开头，以 / 结尾（除了根路径）
    let base = envBase.startsWith('/') ? envBase : `/${envBase}`
    if (base !== '/' && !base.endsWith('/')) {
      base = `${base}/`
    }
    return base
  }
  // 默认根路径
  return '/'
}

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'Odometer' }
      },
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/User/index.vue'),
        meta: { title: '用户管理', icon: 'User' }
      },
      {
        path: 'permissions',
        name: 'Permissions',
        component: () => import('@/views/Permissions/index.vue'),
        meta: { title: '权限管理', icon: 'Avatar' }
      },
      {
        path: 'menu',
        name: 'Menu',
        component: () => import('@/views/Menu/index.vue'),
        meta: { title: '菜单管理', icon: 'Menu', hidden: true }
      },
      {
        path: 'logs',
        name: 'Logs',
        component: () => import('@/views/Logs/index.vue'),
        meta: { title: '日志管理', icon: 'Document' }
      },
      {
        path: 'backups',
        name: 'Backups',
        component: () => import('@/views/Backups/index.vue'),
        meta: { title: '备份管理', icon: 'FolderOpened' }
      },
      {
        path: 'health',
        name: 'Health',
        component: () => import('@/views/Health/index.vue'),
        meta: { title: '健康检查', icon: 'Monitor' }
      },
      {
        path: 'notifications',
        name: 'Notifications',
        component: () => import('@/views/Notifications/index.vue'),
        meta: { title: '通知管理', icon: 'Bell' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(getBasePath()),
  routes
})

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  const userStore = useUserStore()
  
  // 如果有 token 但用户信息为空，刷新用户信息
  if (userStore.token && !userStore.userInfo) {
    try {
      await userStore.getUserInfoAction()
    } catch (error) {
      // 如果获取用户信息失败，清除 token 并跳转到登录页
      userStore.logout()
      next({ name: 'Login', query: { redirect: to.fullPath } })
      return
    }
  }
  
  if (to.meta.requiresAuth && !userStore.token) {
    next({ name: 'Login', query: { redirect: to.fullPath } })
  } else if (to.path === '/login' && userStore.token) {
    next({ path: '/' })
  } else {
    next()
  }
})

export default router

